<template>
  <div>
    <a-modal :title="detail.type == 'add' ? '新增SPU' : '编辑SPU'" :visible="visible" @before-open="open" @before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" :top="20" :width="1200" :mask-closable="false">
      <a-alert type="warning">当规格变化的时候，请刷新规格。重新生成SKU数据</a-alert>
      <a-tabs size="mini" v-model:active-key="currentPage" class="mt10">
        <a-tab-pane key="1" title="基础信息">
          <div class="con-top">
            <div class="img">
              <UplaodImg :style="{ width: '100%', height: '100%' }" @uploadSuccess="imgUploadSuccess" v-model="form.spuPic" :limit="1" />
            </div>
            <div class="form">
              <a-form auto-label-width ref="formRef" size="medium" :model="form" :rules="rules">
                <a-space direction="vertical" :size="24">
                  <a-row>
                    <a-col :span="24">
                      <a-form-item field="spuName" label="SPU名称">
                        <a-input v-model="form.spuName" max-length="200" show-word-limit />
                        <!-- <a-select v-model="form.warehouseCode" allow-clear placeholder="请选择" allow-search :fallback-option="() => ''">
                      <a-option v-for="item of houseList" :value="item.warehouseCode" :label="item.warehouseName"></a-option>
                    </a-select> -->
                      </a-form-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-item field="spu" label="SPU">
                        <a-input v-model="form.spu" max-length="50" show-word-limit :disabled="detail.type == 'edit'">
                          <template #append v-if="detail.type != 'edit'">
                            <a-button type="primary" @click="autoCreateSpu" :loading="autoCreateSpuLoading" :disabled="createSpuRule && !createSpuRule.enable">生成SPU</a-button>
                          </template>
                        </a-input>
                        <a-button type="text" @click="skuRule.visible = true" v-if="detail.type != 'edit'">设置SPU生成规则</a-button>
                      </a-form-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-item field="categoryId" label="产品类目">
                        <a-cascader @change="cateGoryChange" :check-strictly="false" :options="categoryOptions" :field-names="{ value: 'id', label: 'name' }" v-model="form.categoryId" placeholder="全部类目" allow-clear />
                      </a-form-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-item field="developerId" label="产品开发员">
                        <a-select v-if="isCurUser" @change="developerChange" class="second" v-model="form.developerId" :max-tag-count="1" allow-search allow-clear placeholder="请选择">
                          <a-option :label="item.userName" :value="item.id" v-for="item of userList"></a-option>
                        </a-select>
                        <div v-else>{{ $extract(form, 'developer.name') }}</div>
                      </a-form-item>
                    </a-col>

                    <a-col :span="12">
                      <a-form-item field="deptId" label="开发部门">
                        <a-select @change="deptChange" class="second" v-model="form.deptId" allow-search allow-clear placeholder="请选择">
                          <a-option :label="item.deptName" :value="item.id" v-for="item of currentCompanyList"></a-option>
                        </a-select>
                      </a-form-item>
                    </a-col>

                    <a-col :span="12">
                      <a-form-item label="品牌">
                        <a-select @change="brandChange" v-model="form.brandId" allow-clear allow-search placeholder="请选择">
                          <a-option :label="item.name" :value="item.id" v-for="item of brandList"></a-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                    <a-col :span="24">
                      <a-form-item label="产品标签">
                        <span v-for="tag of selTagList" class="tag-btn" :style="{ backgroundColor: tag.color }">{{ tag.name }}</span>
                        <a-tag class="cursor" color="arcoblue" size="small" bordered @click="tag.visible = true">添加标签</a-tag>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-space>
              </a-form>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" title="产品规格">
          <ProductSpecification v-if="visible" ref="productSpecification" :userList="userList" :spu="form.spu" :formRef="formRef" />
        </a-tab-pane>
        <a-tab-pane key="3" title="产品图">
          <AddSpuPic v-if="visible" :setFirtImg="setFirtImg" ref="addSpuPic" />
        </a-tab-pane>
        <a-tab-pane key="4" title="报关/包装/箱规">
          <OverheadInfo v-if="visible" ref="overheadInfo" />
        </a-tab-pane>
        <a-tab-pane key="5" title="产品资料">
          <UploadSkuInfo v-if="visible" ref="uploadSkuInfo" />
        </a-tab-pane>
        <a-tab-pane key="6" title="刊登描述">
          <PublicationDel v-if="visible" ref="publicationDel" />
        </a-tab-pane>
        <a-tab-pane key="7" title="产品属性">
          <ProductProperty v-if="visible" ref="productProperty" :type="detail.type" :propertyList="propertyList" />
        </a-tab-pane>
      </a-tabs>

      <template #footer>
        <a-button class="gray-outline" @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="loading" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
  </div>

  <SkuRule ref="skuRule" @save="getRule" />
  <Tag ref="tag" @save="getTag" :list="selTagList" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, nextTick, computed } from 'vue'
  import { getOrganizesUser } from '@/api/system'
  import { getBrandList, findDeptList, getByCompanyId, genSkuByConfig, batchUpdateSkipNullById, searchSpuDetail, getPropTemplateByCateIdRec, spuUpdateRelatedV2 } from '@/api/product'
  import { Message } from '@arco-design/web-vue'
  import { treeFindPath } from '@/utils/index'
  import SkuRule from './setSkuRule.vue'
  import UplaodImg from '@/components/uploadImg.vue'
  import Tag from '@/views/product/productManagement/productList/tag/tagList.vue'
  import AddSpuPic from './addSpuPic.vue'
  import OverheadInfo from './overheadInfo.vue'
  import UploadSkuInfo from './uploadSkuInfo.vue'
  import PublicationDel from './publicationDel.vue'
  import ProductSpecification from './productSpecification.vue'
  import ProductProperty from './productProperty.vue'
  export default defineComponent({
    props: ['categoryOptions', 'detail'],
    components: { SkuRule, UplaodImg, Tag, AddSpuPic, OverheadInfo, UploadSkuInfo, PublicationDel, ProductSpecification, ProductProperty },
    setup(props: any, { emit }) {
      const isCurUser = computed(() => {
        let item = data.userList.find((item: any) => item.id == data.form.developerId)
        return item ? true : false
      })
      let visible = ref(false)
      const formRef = ref()
      const skuRule = ref()
      const tag = ref()
      const addSpuPic = ref()
      const overheadInfo = ref()
      const uploadSkuInfo = ref()
      const publicationDel = ref()
      const productSpecification = ref()
      const productProperty: any = ref()
      const data: any = reactive({
        form: {},
        rules: {
          spuName: [{ required: true, message: '请输入SPU名称' }],
          spu: [{ required: true, message: '请输入SPU' }],
          categoryId: [{ required: true, message: '请选择产品类目' }],
          developerId: [{ required: true, message: '请选择产品开发员' }],
        },
        loading: false,
        autoCreateSpuLoading: false,
        categoryList: [],
        userList: [],
        brandList: [],
        createSpuRule: {},
        currentPage: '1',
        selTagList: [],
        detailInfo: {},
        propertyList: [],
        currentCompanyList: [],
      })

      const open = () => {
        getUserList()
        getBrand()
        getRule()
        getCompanyList()
        data.currentPage = '1'
        if (props.detail.type == 'edit') {
          getDetial(props.detail.data.id)
        }
      }

      const getCompanyList = async () => {
        let res = await findDeptList()
        data.currentCompanyList = res?.data || []
      }

      // 选择开发部门
      const deptChange = (val: string) => {
        let deptItem = data.currentCompanyList.find((item: any) => item.id === val)
        data.form.developer.deptName = deptItem.deptName
        data.form.developer.deptId = deptItem.id
      }

      const getDetial = async (id: string) => {
        const res: any = await searchSpuDetail(id)
        let info: any = res?.data || {}
        data.detailInfo = info
        data.form = info

        data.form.spuPic = info?.productPicList ? info?.productPicList[0]?.url : ''
        data.form.categoryId = info?.category?.id || ''
        data.form.developerId = info?.developer?.id || ''
        data.form.deptId = info?.developer?.deptId || ''
        data.form.brandId = info?.brand?.id || ''
        data.selTagList = info.tagList
        // data.specList = info.specList
        // data.productSkuList = info.productSkuList.map((e: any) => {
        //   if (!e.productPicList) {
        //     let arr = [{ url: '' }]
        //     e.productPicList = arr
        //   }
        //   return e
        // })
        // 获取属性模板
        getProTem(data.form.categoryId)
        // 编辑的时候回显规格
        productSpecification.value.init(info)
        // 编辑回显产品图
        addSpuPic.value.init(info)
        // 编辑的时候回显报关等信息
        overheadInfo.value.init(info)
        // 产品资料
        uploadSkuInfo.value.init(info)
        // 刊登详情
        publicationDel.value.init(info)
      }

      // 获取属性模板
      const getProTem = async (id: string) => {
        data.propertyList = []
        let params = {
          pageNum: 1,
          pageSize: 9999,
          categoryId: id,
        }
        const res: any = await getPropTemplateByCateIdRec(params)
        data.propertyList = res.data?.itemList || []
        // 属性详情回显
        productProperty.value.init(data.form.propList || [], data.propertyList)
      }

      const handleOk = () => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            let specList = productSpecification.value.specList
            let productSkuList = productSpecification.value.autoCreateList
            let picList = addSpuPic.value.productPicList
            let propList = productProperty.value.showValueList
            // if (!productSkuList[0]) {
            //   return Message.error('请生成sku信息')
            // }
            // 校验属性信息
            for (let i = 0; i < propList.length; i++) {
              const e = propList[i]
              let num = 0
              if (e.type == 8 || e.type == 7) {
                num = e.valueStrList.filter((e: any) => e).length
              }
              if (e.type == 1 && !e.valueStr && e.propRequired) {
                Message.error(`请选择${e.name}`)
                return false
              } else if (e.type == 2 && !e.valueStrList[0] && e.propRequired) {
                Message.error(`请选择${e.name}`)
                return false
              } else if (e.type == 4 && !e.valueStr && e.propRequired) {
                Message.error(`请选择${e.name}`)
                return false
              } else if (e.type == 5 && !e.valueNumber && e.propRequired) {
                Message.error(`请输入${e.name}`)
                return false
              } else if (e.type == 6 && !e.valueBigDecimal && e.propRequired) {
                Message.error(`请输入${e.name}`)
                return false
              } else if (e.type == 7 && num != 3 && e.propRequired) {
                Message.error(`请输入${e.name}`)
                return false
              } else if (e.type == 8 && num != 2 && e.propRequired) {
                Message.error(`请输入${e.name}`)
                return false
              }
            }

            let params = {
              ...data.form,
              productPicList: picList,
              tagList: data.selTagList,
              specList: specList,
              productVideoList: addSpuPic.value.productVideoList,
              productAddPicList: addSpuPic.value.productAddPicList,
              declaration: overheadInfo.value.form,
              boxSpecList: overheadInfo.value.list,
              packingList: overheadInfo.value.packList,
              productInfoList: uploadSkuInfo.value.list,
              publish: publicationDel.value.publish,
              productSkuList: [],
              removeProductSkuIdList: productSpecification.value.removeProductSkuIdList,
              propList: propList,
            }

            if (productSkuList[0]) {
              productSkuList.forEach((e: any) => {
                let obj = {
                  ...e,
                  sku: e.sku,
                  skuName: e.skuName,
                  productType: 'normal',
                  skuType: 'PRODUCT',
                  volume: {
                    height: e.heightNum,
                    length: e.lengthNum,
                    unit: e?.volume?.unit || 'cm',
                    width: e.widthNum,
                  },
                  weight: {
                    unit: e?.weight?.unit || 'g',
                    weight: e.weightNum,
                  },
                  salerIdList: e.salerIdList,

                  status: props.detail.type != 'edit' ? 'ACTIVE' : e.status,
                }

                if (e.skuImg) {
                  obj.productPicList = [
                    {
                      url: e.skuImg,
                    },
                  ]
                }

                params.productSkuList.push(obj)
              })
            }
            if (data.form.spuPic) {
              let urlStr = ''
              data.form.spuPic instanceof Array ? (urlStr = data.form.spuPic[0].url) : (urlStr = data.form.spuPic)
              let index = params.productPicList.findIndex((e: any) => e.url == urlStr)
              if (index == -1) params.productPicList.unshift({ url: urlStr })
            }

            try {
              data.loading = true

              // const res: any = await updateProductSPUList(params)
              const res: any = await batchUpdateSkipNullById({ updateDocList: [params] })
              if (res.code == 'SUCCESS') {
                handleCancel()
                props.detail.type == 'add' ? Message.success('创建成功') : Message.success('编辑成功')
                visible.value = false
                emit('save')
              }
            } catch (error) {}

            data.loading = false
          }
        })
      }
      const getUserList = async () => {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res: any = await getOrganizesUser(params)
        data.userList = res?.data?.records
      }

      const getBrand = async () => {
        let params = {
          pageNum: 1,
          pageSize: 99999,
        }
        const res = await getBrandList(params)
        data.brandList = res?.data?.records || []
      }

      const handleCancel = () => {
        formRef.value.resetFields()
        formRef.value.clearValidate()
        productSpecification.value.specList = []
        productSpecification.value.autoCreateList = []
        productSpecification.value.selIndexs = []
        data.selTagList = []
        data.form = {}
        data.loading = false
        visible.value = false
      }

      // 选择类目
      const cateGoryChange = (val: any) => {
        if (val) {
          let category = {
            fullName: '',
            highParentName: '',
            id: '',
            name: '',
          }
          let arr: any = treeFindPath(props.categoryOptions, (data: any) => data.id == val)
          category.highParentName = arr[0].name
          category.id = arr[arr.length - 1].id
          category.name = arr[arr.length - 1].name
          data.form.category = category
        } else {
          delete data.form.category
        }
        getProTem(val)
      }

      const getRule = async () => {
        const res = await getByCompanyId()
        data.createSpuRule = res?.data || {}
      }

      const autoCreateSpu = () => {
        formRef.value.validateField('categoryId', async (valid: any) => {
          if (!valid) {
            data.autoCreateSpuLoading = true
            const res = await genSkuByConfig({ categoryId: data.form.categoryId })
            data.autoCreateSpuLoading = false
            data.form.spu = res?.data || ''
            formRef.value.clearValidate()
          }
        })
      }

      // 选择开发人员
      const developerChange = (val: any) => {
        // if (val) {
        let developer = {
          id: '',
          name: '',
          companyId: '',
          deptId: '',
          deptName: '',
        }
        let obj = data.userList.find((el: any) => val == el.id)
        if (obj) {
          developer.id = obj.id
          developer.name = obj.userName
          developer.companyId = obj.companyId
          developer.deptId = obj.deptId
          developer.deptName = obj.deptName
        }
        data.form.deptId = obj.deptId
        data.form.developer = developer
        // } else {
        //   delete data.form.developer
        // }
      }

      // 选择品牌
      const brandChange = (val: any) => {
        if (val) {
          let brand = {
            code: '',
            id: '',
            name: '',
          }
          let obj: any = data.brandList.find((el: any) => val == el.id)

          if (obj) {
            brand.id = obj.id
            brand.code = obj.code
            brand.name = obj.name
          }
          data.form.brand = brand
        } else {
          delete data.form.brand
        }
      }

      const getTag = (list: any) => {
        data.selTagList = list
      }

      const imgUploadSuccess = () => {
        addSpuPic.value.productPicList.push({ url: data.form.spuPic })
      }

      const setFirtImg = (list: any) => {
        data.form.spuPic = list[0]?.url || ''
      }

      return {
        ...(toRefs(data) as any),
        visible,
        formRef,
        open,
        handleOk,
        handleCancel,
        cateGoryChange,
        skuRule,
        getRule,
        autoCreateSpu,
        developerChange,
        brandChange,
        tag,
        getTag,
        addSpuPic,
        overheadInfo,
        uploadSkuInfo,
        publicationDel,
        imgUploadSuccess,
        setFirtImg,
        productSpecification,
        productProperty,
        isCurUser,
        deptChange,
      }
    },
  })
</script>

<style lang="less" scoped>
  :deep(.arco-input-append) {
    padding: 0;
  }
  :deep(.arco-btn-primary) {
    border-radius: 0;
  }
  :deep(.arco-upload-picture-card) {
    width: 160px;
    height: 160px;
  }
  :deep(.arco-upload-list-picture) {
    width: 160px;
    height: 160px;
  }

  .tag-btn {
    height: 20px;
    line-height: 20px;
    padding: 0 5px;
    color: white;
    margin-right: 5px;
  }

  .con-top {
    // width: 100%;
    display: flex;
    margin: 10px;
    .img {
      width: 160px;
      height: 160px;
      // border: 1px solid red;
    }

    .form {
      flex: 1;
    }
  }
</style>
